import React, {useState, useEffect, forwardRef, useImperativeHandle} from 'react'
import {Row, Col, Form, Input, Select, Button, Space, Modal, Spin, message} from 'antd'
import './../neibin/inside.less'
// import {cardType, sexType} from './config'
import Loader from '@/components/loader/loader'
import UseCamera from '../neibin/face'
var getUserInfo:any = null
var ws: any = null
var FormContent = (props: any, ref: any):any => {
  const {Option} = Select
  var cancelList: Function[] = []
  const [form] = Form.useForm()
  const [mapList, setmapList] = useState<any[]>([]);
  const [visible, setvisible] = useState(false) //弹窗开关
  const [isSpinning, setisSpinning] = useState<boolean>(false); // 展示loading
  const [showPhoto, setshowPhoto] = useState<boolean>(false); // 是否展示拍摄按钮
  // const [user_id, setuser_id] = useState<any>(''); // id
  const [spinTitle, setspinTitle] = useState<string | undefined>('正在唤醒读卡器');
  const [isconnect, setisconnect] = useState<boolean>(false); // websocket是否联通
  // const onFinish = (values: any) => {
  //   form.validateFields().then(res=>{
  //     console.log(1)
  //   }).catch(res=>{
  //     console.log(2)
  //   })
  // };
  // const onFinishFailed = (errorInfo: any) => {
  //   console.log('Failed:', errorInfo);
  // };  
  const formWarp = [
    {
      isHalf: true,
      key: 1,
      children: [
        {
          label: '姓名',
          name: 'name',
          isImg: false,
          key: 2,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '性别',
          name: 'gender',
          isImg: false,
          key: 3,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '出生日期',
          name: 'birthday',
          isImg: false,
          key: 4,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '民族',
          name: 'nation',
          isImg: false,
          key: 5,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        }                 
      ]
    },  
    {
      label: '证件类型',
      name: 'user_cardType',
      isImg: false,
      isHalf: false,
      key: 6,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    },  
    {
      label: '证件号码',
      name: 'idCardNo',
      isImg: false,
      isHalf: false,
      key: 7,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    } ,  
    {
      label: '户籍地址',
      name: 'address',
      isImg: false,
      isHalf: false,
      key: 8,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    },
    {
      label: '',
      name: 'photo',
      isImg: true,
      isHalf: false,
      imgTitle: '身份证照片',
      key: 10,
      rules: [{ required: true, message: '请读取身份证信息' }]
    },  
    {
      label: '',
      name: 'imgNow',
      isImg: true,
      isHalf: false,
      imgTitle: '现场比对照片',
      key: 11,
      rules: [{ required: true, message: '请点击拍摄现场照片' }]
    }  
  ]
  const visitor = [
    {
      isHalf: true,
      key: 1,
      children: [
        {
          label: '姓名',
          name: 'name',
          isImg: false,
          key: 2,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '性别',
          name: 'gender',
          isImg: false,
          key: 3,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '出生日期',
          name: 'birthday',
          isImg: false,
          key: 4,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        },
        {
          label: '民族',
          name: 'nation',
          isImg: false,
          key: 5,
          render: ()=>{
            return <Input disabled></Input>
          },
          rules: [{ required: true, message: '请选择证件类型' }]          
        }                 
      ]
    },  
    {
      label: '证件类型',
      name: 'user_cardType',
      isImg: false,
      isHalf: false,
      key: 6,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    },  
    {
      label: '证件号码',
      name: 'idCardNo',
      isImg: false,
      isHalf: false,
      key: 7,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    } ,  
    {
      label: '户籍地址',
      name: 'address',
      isImg: false,
      isHalf: false,
      key: 8,
      render: ()=>{
        return <Input disabled></Input>
      },
      rules: [{ required: true, message: '请选择证件类型' }]
    },
    {
      label: '访问事由',
      name: 'remark',
      isImg: false,
      isHalf: false,
      key: 8,
      render: ()=>{
        return <Input className='remark' style={{background: '#fff'}} type='textarea'></Input>
      }
    },    
    {
      label: '',
      name: 'photo',
      isImg: true,
      isHalf: false,
      imgTitle: '身份证照片',
      key: 10,
      rules: [{ required: true, message: '请读取身份证信息' }]
    },  
    {
      label: '',
      name: 'imgNow',
      isImg: true,
      isHalf: false,
      imgTitle: '现场比对照片',
      key: 11,
      rules: [{ required: true, message: '请点击拍摄现场照片' }]
    }  
  ]
  const toJson = (data: any)=>{
    return JSON.stringify(data)
  }
  useImperativeHandle(ref, ()=>{
    return form
  }, [form])  
  useEffect(() => {
    // GetData({name: 1}).then(res=>{
    //   console.log(11)
    // })
    if(props.editConfig.type === 'edit') {
      setmapList([...formWarp])
    } else {
      setmapList([...visitor])
    }

  }, [props.editConfig.type])
  useEffect(()=>{   
    ws = new WebSocket("ws://localhost:3000");
    ws.onopen = function(evt: any) { 
      console.log('成功');
      
      ws.send(toJson({type: 0, message: '成功'}))
      setisconnect(true)
    };
    
    ws.onmessage = function(evt: any) {
      if(evt.data) {      
        let obj = JSON.parse(evt.data)
        if(obj.type && obj.type === '1') {
          let formData = {...obj.returndata}
          formData.user_cardType = '身份证'
          formData.photo = `data:image/png;base64,${formData.photo}`
          form.setFieldsValue(formData)
          setshowPhoto(true)
          setisSpinning(false)
        }
        if(obj.type === '2') {
          getImg(`data:image/png;base64,${obj.data}`)
          setvisible(false)
          message.success({content: '比对成功', key: 'upload', duration: 3});
        }
      }
    };
    
    ws.onclose = function(evt: any) {  
    };      
    return () => {
      cancelList.forEach((fn)=>{
        fn()
      })
      clearInterval(getUserInfo)
    }
  }, [])
  // const getBase64=(img:any)=>{
  //   const base64Url = `data:image/png;base64,${window.btoa(
  //     new Uint8Array(img).reduce(
  //       (data, byte) => data + String.fromCharCode(byte),
  //       ""
  //     )
  //   )}`;
  //   console.log(base64Url);
    
  //   return base64Url;
  // }
  const getCard = ()=>{   
    setisSpinning(true)  
      setTimeout(()=>{    
        if(ws.readyState === 1) {
          setspinTitle('已唤醒读卡器，等待读卡中')
          let sentFrom = JSON.stringify({type: 1, name: '唤醒读卡器'})
          if(isconnect) {
            ws.send(sentFrom)          
          }
        }
        // setTimeout(()=>{
        //   setshowPhoto(true)
        //   setisSpinning(false)
        //   form.setFieldsValue({
        //     address: '人工智能小镇',
        //     birthday: '1993.7.25',
        //     gender: '男',
        //     idCardNo: '3303027xxxxxxxx',
        //     imgNow: '',
        //     name: 'cgz',
        //     nation: '汉族',
        //     user_face: 1,
        //     photo: '',
        //     user_cardType: '身份证'
        //   } )
        //     console.log(form.getFieldsValue())

        // }, 2000)
      }, 500)
    // weakupRC({readcard_id: 1}).then((res: any)=>{
    //   setuser_id(res.data.data || 1)
    //   let num = 0
    //   getUserInfo = setInterval(()=>{
    //     searchUser({user_id: res.data.data}, pushCancel).then((result:any)=>{
    //       num ++ 
    //       let obj = {
    //         "user_id":"123",
    //         "user_attribute":"内宾",
    //         "user_name":"tzj",
    //         "hotel_id":"112",
    //         "user_idnumber":"330184198905214152",
    //         "user_sex":"男",
    //         "user_national":"汉族",
    //         "user_borntime":"1989-05-31",
    //         "user_address":"人工智能小镇",
    //         "user_information":"有证登陆",
    //         "user_face":"true",
    //         "user_checkintime":"2020-11-04 12:15:16",
    //         "user_img": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1604555161&di=652f05944b832ec4a564bdca140461a3&src=http://a3.att.hudong.com/57/28/01300000921826141405283668131.jpg"
    //       }
    //       if(result.data.code == '0') {
    //         let formData = {...result.data.data}
    //         formData.user_cardType = '身份证'
    //         formData.user_img = getBase64(formData.user_img)
    //         form.setFieldsValue(formData || obj)
    //         setshowPhoto(true)
    //         setisSpinning(false)
    //         clearInterval(getUserInfo)
    //         message.success('身份证读取成功，下一步请点击拍摄现场照片进行人脸比对！', 3);
    //         cancelList.forEach(fn=>{ // 取消后续请求
    //           fn()
    //         })            
    //       }
    //     }).catch(err=>{
    //       setisSpinning(false)
    //       clearInterval(getUserInfo)          
    //     })
    //     if(num >= 30) {
    //       message.warning('读卡超时或者长时间未操作，请重新点击', 2);
    //       setisSpinning(false)
    //       clearInterval(getUserInfo)         
    //     }
    //   },2000) 
    // })
  
  }
  const takePhoto = ()=>{
    setvisible(true)
  }
  // const pushCancel = (fn: any) =>{ // 将cancletoken的回调推到数组
  //   cancelList.push(fn)
  // }  
  const handleOk = () => {
    setvisible(false)
  }
  const getImg =(img: any)=> {
    form.setFieldsValue({'imgNow': img})
  }
    return (
      <div className='sanke_form'>
      <Spin tip={spinTitle} spinning={isSpinning}>
        <Form
          name="basic"
          form={form}
          labelAlign='left'
        >            
          <Row>
            <Col span={12}>
              <Form.Item label='上传证件'>
                <Space>
                  <Button type='primary' onClick={getCard}>读取证件</Button>
                  {showPhoto ? <Button type='primary' onClick={takePhoto}>拍摄现场照片</Button> : null}
                </Space>
              </Form.Item> 
              {showPhoto ? <div> 
                {
                  props.editConfig.roomTitle ? <Form.Item
                    label={props.editConfig.roomTitle}
                  >
                    <span>{props.editConfig.roomNum}</span>
                  </Form.Item> : null
              
                }
                {
                  mapList.map((item: any, index)=>{
                    return item.isHalf ? <div key={index + 'ss'} className='doubleContent'>
                      {item.children.map((val: any, i: any)=>{
                        return <Form.Item
                        label={val.label}
                        name={val.name}
                        rules={val.rules}
                        key={i + val.name}
                      >
                        {val.render()}
                      </Form.Item>
                      })}
                    </div> : !item.isImg ? <Form.Item
                    label={item.label}
                    name={item.name}
                    rules={item.rules}
                    key={index + item.name}
                  >
                    {item.render()}
                  </Form.Item> : null
                  })
                }                                                        
              </div> : null }      
            </Col>
            {showPhoto ? <Col offset={2} className='imgContent' span={10}>
                <div className='imgBox'>
                {
                  mapList.map((val, i)=>{
                    return val.isImg ? <Form.Item
                      name={val.name}
                      rules={val.rules}
                      key={i}    
                      style={{margin: 20}}               
                      >              
                      <Loader disabled imgTitle={val.imgTitle} imageUrl={form.getFieldValue(val.name)} style={{width: 143, height: 215}}></Loader>
                    </Form.Item> : null
                  })
                }
                </div>
            </Col> : null}
          </Row>   
          </Form>    
            <Modal
              getContainer={false}
              title='人脸对比识别'
              visible={visible}
              width={600}  
              onOk={handleOk}
              onCancel={handleOk}   
              maskClosable={false}
              footer={
                []
              }         
            >
            {visible ? <UseCamera ws={ws} getImg={getImg} handleOk={handleOk} visible={visible}/> : null} 
            </Modal>   
          </Spin>            
      </div>
    )
}
FormContent = forwardRef(FormContent);
export default FormContent
